﻿using QntPlatform.Db;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Timers;


namespace QntPlatform
{
    public class SysFun : ISysFun
    {
        public SysFun(Robot robot) : base(robot)
        {
        }
        
    }
    public  class ISysFun:IDisposable
    {
        Robot robot;

        public ISysFun(Robot robot)
        {
            this.robot = robot;
        }
       internal void Init() {
            timer = new Timer(2000);
            timer.Elapsed += (p1, p2) =>
            {
                try
                {
                    Timer1sEvent?.Invoke(p1, p2.SignalTime);
                }
                catch (Exception ex)
                {
                    Log.Default().Error(ex);
                    throw;
                };
            };
           // timer.Start();
            StrParse = new StrParse();
        }
        Timer timer;

         public event EventHandler<string> CommandEvent;
        public event EventHandler<DateTime> Timer1sEvent;
        public void OnCmdHandle(string cmd)
        {
            CommandEvent?.Invoke(this, cmd);
        }

        public IDictionary<string,object> GetRobotContext()
        {
            return robot.context;
        }
       
       public string Storage(string key){
           var re= DbManager.GetDb().Select<RobotData>().Where(p=>p.RobotId==robot.Id&&p.Key==key).First();
           return re?.Value;
       }
       public void Storage(string key,string value){
           var data=new RobotData(){ RobotId=robot.Id,Key=key,Value=value};
           var re= DbManager.GetDb().Delete<RobotData>().Where(p=>p.RobotId==robot.Id&&p.Key==key).ExecuteAffrows();
           DbManager.GetDb().Insert(data);
       }
       
        /// <summary>
        /// 动态执行，未完成
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool show(object obj)
        {
            var query = new[] { this }.AsQueryable();
            query.FirstOrDefault("show(this)");
            //
            StrParse strParse = new StrParse();
            var re = strParse.ToText(obj);
            Console.WriteLine(re);
            return true;
        }
        public static decimal calcUnitProfit(decimal nowPrice, decimal buyPrice, bool isLong = true)
        {
            return isLong ? nowPrice - buyPrice : -(nowPrice - buyPrice);
        }
        /** 单位利润率，负值表示亏损
  * @param {Number} nowPrice 当前价
  * @param {Number} buyPrice 买入价
  * @param {Boolean} direction 是否多单，默认多单
  */
      public static decimal CalcProfitRate(decimal nowPrice, decimal buyPrice, bool isLong = true)
        {
            return isLong ? nowPrice / buyPrice - 1 : -(nowPrice / buyPrice - 1);
        }

        /// <summary>
        ///  profitRate负值表示亏损率，正值表示盈利率
        /// </summary>
        /// <param name="profitRate"></param>
        /// <param name="buyPrice"></param>
        /// <param name="isLong"></param>
        /// <returns></returns>
        public static decimal CalcPriceByProfitRate(decimal profitRate, decimal buyPrice, bool isLong = true)
        {
            if (isLong)
                return buyPrice * (1 + profitRate);
            return buyPrice * (1 - profitRate);
        }
        public int GetRobotInfo() {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 获取进程id
        /// </summary>
        /// <returns></returns>
        public int GetPid() {
            
            return System.Threading.Thread.CurrentThread.ManagedThreadId;
        }
        IStrParse StrParse=new StrParse();
        public string ToText<T>(T obj) {
          return  StrParse.ToText(obj);
        }
        public T ParseTo<T>(string txt) {
            return StrParse.Parse<T>(txt);
        }

        public void Dispose()
        {
            timer.Close();
        }
    }
}